{% load i18n static %}

<script type="text/x-template" id="suit-login">
  <a-form
    id="components-form-login"
    :form="form"
    class="login-form"
    @submit="handleSubmit"
  >
    <a-form-item>
      <a-input
        v-decorator="[
          'username',
          { rules: [{ required: true, message: '用户名称不能为空!' }] },
        ]"
        placeholder="Username"
      >
        <a-icon slot="prefix" type="user" style="color: rgba(0,0,0,.25)"></a-icon>
      </a-input>
    </a-form-item>
    <a-form-item>
      <a-input
        v-decorator="[
          'password',
          { rules: [{ required: true, message: '用户密码不能为空!' }] },
        ]"
        type="password"
        placeholder="Password"
      >
        <a-icon slot="prefix" type="lock" style="color: rgba(0,0,0,.25)"></a-icon>
      </a-input>
    </a-form-item>
    <a-form-item>
      <a-checkbox
        v-decorator="[
          'remember',
          {
            valuePropName: 'checked',
            initialValue: false,
          },
        ]"
      >
        Remember me
      </a-checkbox>
      <a class="login-form-forgot" href="{% url 'accounts:reset' %}">
        Forgot password
      </a>
      <a-button type="primary" html-type="submit" class="login-form-button">
        Log in
      </a-button>
      Or
      <a href="{% url 'accounts:register' %}">
        register now!
      </a>
    </a-form-item>
  </a-form>
</script>

<script type="application/javascript">
  Vue.component('suit-login', {
    delimiters: ['<%', '%>'],
    template: '#suit-login',
    beforeCreate() {
      this.form = this.$form.createForm(this, { name: 'login_form' });
    },
    methods: {
      handleSubmit(e) {
        e.preventDefault();
        this.form.validateFields((err, values) => {
          if (!err) {
            const form = new FormData();
            form.append('username', values.username);
            form.append('password', values.password);
            form.append('remember', values.remember);
            axios({
              url: "{% url 'accounts:login' %}",
              method: "POST",
              data: form,
              headers: {
                'content-type': `multipart/form-data; boundary=${form._boundary}`,
              },
            }).then(response => {
              const {code, data} = response.data;
              if (code === "00000000") {
                self.location="/client/";
              }
            }).catch(error => {
              const {meta, data} = error.response.data;
              Bus.$emit('notification', 'error', meta.code, meta.details);
            });
          }
        });
      },
    },
  });
</script>